// 组织架构管理模块
class OrgStructureManager {
    // 组织数据存储
    static orgData = [
        { id: 1, name: '总部', code: 'HEAD', type: '总部', parentId: 0, leader: '校长', memberCount: 2000, status: 'active' },
        { id: 2, name: '计算机学院', code: 'CS', type: '学院', parentId: 1, leader: '王院长', memberCount: 156, status: 'active' },
        { id: 3, name: '软件工程系', code: 'SE', type: '系部', parentId: 2, leader: '李主任', memberCount: 42, status: 'active' },
        { id: 4, name: '2023级软件1班', code: 'SE202301', type: '班级', parentId: 3, leader: '张老师', memberCount: 35, status: 'active' },
        { id: 5, name: '2023级软件2班', code: 'SE202302', type: '班级', parentId: 3, leader: '李老师', memberCount: 32, status: 'active' },
        { id: 6, name: '电子信息学院', code: 'EE', type: '学院', parentId: 1, leader: '赵院长', memberCount: 120, status: 'active' },
        { id: 7, name: '电子工程系', code: 'EEDE', type: '系部', parentId: 6, leader: '孙主任', memberCount: 38, status: 'active' }
    ];

    // 获取所有组织数据
    static getAllOrganizations() {
        return [...this.orgData]; // 返回副本，防止直接修改原始数据
    }

    // 根据ID获取组织
    static getOrganizationById(id) {
        return this.orgData.find(org => org.id === id);
    }

    // 根据上级ID获取子组织
    static getOrganizationsByParentId(parentId) {
        return this.orgData.filter(org => org.parentId === parentId);
    }
    
    // 事件调度器
    static eventListeners = [];
    
    // 注册事件监听
    static onOrgDataChange(callback) {
        this.eventListeners.push(callback);
        return () => {
            this.eventListeners = this.eventListeners.filter(listener => listener !== callback);
        };
    }
    
    // 触发组织数据变化事件
    static dispatchOrgDataChange() {
        this.eventListeners.forEach(callback => {
            try {
                callback();
            } catch (error) {
                console.error('处理组织数据变化事件失败:', error);
            }
        });
    }

    // 新增组织
    static addOrganization(org) {
        const newOrg = { ...org, id: Date.now() };
        this.orgData.push(newOrg);
        this.dispatchOrgDataChange();
        return newOrg;
    }

    // 更新组织
    static updateOrganization(id, org) {
        const index = this.orgData.findIndex(item => item.id === id);
        if (index !== -1) {
            this.orgData[index] = { ...this.orgData[index], ...org };
            this.dispatchOrgDataChange();
            return this.orgData[index];
        }
        return null;
    }

    // 删除组织
    static deleteOrganization(id) {
        const index = this.orgData.findIndex(item => item.id === id);
        if (index !== -1) {
            const deletedOrg = this.orgData.splice(index, 1)[0];
            this.dispatchOrgDataChange();
            return deletedOrg;
        }
        return null;
    }

    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                配置系统的组织架构，包括部门、学院、班级等层级结构。
            </div>

            <div class="actions">
                <button class="btn btn-primary btn-add-org"><i class="fas fa-plus"></i> 新增组织</button>
                <button class="btn btn-default btn-edit-org-batch"><i class="fas fa-edit"></i> 修改组织</button>
                <button class="btn btn-danger btn-delete-org-batch"><i class="fas fa-trash"></i> 删除组织</button>
                <div class="search-area">
                    <input type="text" id="search-org-input" placeholder="搜索组织名称...">
                    <button id="search-org-btn" class="btn btn-primary"><i class="fas fa-search"></i> 搜索</button>
                </div>
            </div>
            
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllOrgs"></th>
                            <th>组织名称</th>
                            <th>组织代码</th>
                            <th>组织类型</th>
                            <th>上级组织</th>
                            <th>负责人</th>
                            <th>成员数量</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${this.orgData.map(org => `
                            <tr>
                                <td><input type="checkbox" class="rowCheckbox"></td>
                                <td>${org.name}</td>
                                <td>${org.code}</td>
                                <td>${org.type}</td>
                                <td>${this.getOrganizationById(org.parentId)?.name || '-'}</td>
                                <td>${org.leader}</td>
                                <td>${org.memberCount}</td>
                                <td><button class="status-btn ${org.status === 'active' ? 'active' : ''}">${org.status === 'active' ? '启用' : '禁用'}</button></td>
                                <td class="operation">
                                    <a href="#" class="btn-edit-org" data-id="${org.id}"><i class="fas fa-edit"></i> 编辑</a>
                                    <a href="#" class="btn-delete-org" data-id="${org.id}"><i class="fas fa-trash"></i> 删除</a>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
            
            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">4</a>
                <a href="#">5</a>
                <a href="#">下一页</a>
            </div>
        `;

        // 设置全选功能
        mainManager.setupSelectAll('selectAllOrgs', 'rowCheckbox');

        // 设置操作按钮事件
        systemManager.setupActionButtons(container);

        // 绑定新增组织按钮事件
        const addOrgBtn = container.querySelector('.btn-add-org');
        if (addOrgBtn) {
            addOrgBtn.addEventListener('click', AddOrgModal.showModal);
        }

        // 设置搜索功能
        const searchBtn = container.querySelector('#search-org-btn');
        const searchInput = container.querySelector('#search-org-input');

        const executeSearch = () => {
            const keyword = searchInput.value.trim();
            if (!keyword) {
                alert('请输入搜索关键词');
                return;
            }
            OrgStructureManager.performSearch(keyword, container);
        };

        if (searchBtn) {
            searchBtn.addEventListener('click', executeSearch);
        }

        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    executeSearch();
                }
            });
        }

        // 为编辑和删除按钮添加点击事件（使用事件委托）
        const tableBody = container.querySelector('.table-container tbody');
        if (tableBody) {
            tableBody.addEventListener('click', (e) => {
                const editButton = e.target.closest('.btn-edit-org');
                if (editButton) {
                    e.preventDefault();
                    const orgId = parseInt(editButton.dataset.id);
                    const orgData = OrgStructureManager.getOrganizationById(orgId);
                    if (orgData) {
                        EditOrgModal.showModal(orgData);
                    }
                }

                const deleteButton = e.target.closest('.btn-delete-org');
                if (deleteButton) {
                    e.preventDefault();
                    const orgId = parseInt(deleteButton.dataset.id);
                    OrgStructureManager.deleteOrg(orgId, container);
                }
            });
        }
    }

    // 删除组织
    static deleteOrg(orgId, container) {
        const org = OrgStructureManager.getOrganizationById(orgId);
        if (!org) {
            alert('组织不存在');
            return;
        }

        this.showDeleteConfirm(org.name, () => {
            OrgStructureManager.deleteOrganization(orgId);
            alert('删除成功');
            OrgStructureManager.loadContent(container);
        });
    }

    // 显示删除确认弹窗
    static showDeleteConfirm(orgName, onConfirm) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h3>删除确认</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div style="padding: 20px; font-size: 16px; color: #333;">
                    确定要删除组织"${orgName}"吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" id="delete-cancel-btn">取消</button>
                    <button type="button" class="btn btn-danger" id="delete-confirm-btn">确认删除</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#delete-cancel-btn');
        const confirmBtn = modal.querySelector('#delete-confirm-btn');
        const overlay = modal.querySelector('.modal-overlay');

        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        confirmBtn.addEventListener('click', () => {
            onConfirm();
            closeModal();
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });

        setTimeout(() => modal.classList.add('show'), 10);
    }

    // 执行搜索功能
    static performSearch(keyword, container) {
        const tableBody = container.querySelector('.table-container tbody');
        if (!tableBody) return;

        const rows = tableBody.querySelectorAll('tr');
        let foundCount = 0;
        const keywordLower = keyword.toLowerCase();

        rows.forEach(row => {
            const nameCell = row.cells[0];
            const codeCell = row.cells[1];
            const typeCell = row.cells[2];

            let matchFound = false;
            if (nameCell && codeCell && typeCell) {
                const nameText = nameCell.textContent.toLowerCase();
                const codeText = codeCell.textContent.toLowerCase();
                const typeText = typeCell.textContent.toLowerCase();
                matchFound = nameText.includes(keywordLower) ||
                            codeText.includes(keywordLower) ||
                            typeText.includes(keywordLower);
            }

            if (matchFound) {
                row.style.display = '';
                foundCount++;
            } else {
                row.style.display = 'none';
            }
        });

        if (foundCount === 0) {
            alert('未找到匹配的记录');
        }
    }
}

// 新增组织模态框
class AddOrgModal {
    static showModal() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'addOrgModal';

        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>新增组织</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="add-org-form">
                    <div class="form-group">
                        <label for="org-name">组织名称</label>
                        <input type="text" id="org-name" name="name" class="form-control" placeholder="2-50个字符" required>
                        <div class="error-text" id="org-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="org-code">组织代码</label>
                        <input type="text" id="org-code" name="code" class="form-control" placeholder="字母、数字" required>
                        <div class="error-text" id="org-code-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="org-type">组织类型</label>
                        <select id="org-type" name="type" class="form-control" required>
                            <option value="">请选择类型</option>
                            <option value="总部">总部</option>
                            <option value="学院">学院</option>
                            <option value="系部">系部</option>
                            <option value="班级">班级</option>
                        </select>
                        <div class="error-text" id="org-type-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="org-parent">上级组织</label>
                        <select id="org-parent" name="parentId" class="form-control" required>
                            <option value="0">无上级</option>
                        </select>
                        <div class="error-text" id="org-parent-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="org-leader">负责人</label>
                        <input type="text" id="org-leader" name="leader" class="form-control" placeholder="负责人姓名" required>
                        <div class="error-text" id="org-leader-error"></div>
                    </div>
                    <div class="form-group">
                        <label id="org-status-label">状态</label>
                        <div class="custom-radio-group" role="radiogroup" aria-labelledby="org-status-label" style="display: flex; gap: 20px;">
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="org-status-active" name="status" value="active" checked>
                                <label for="org-status-active" style="margin-bottom: 0; margin-left: 8px;">启用</label>
                            </div>
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="org-status-inactive" name="status" value="inactive">
                                <label for="org-status-inactive" style="margin-bottom: 0; margin-left: 8px;">禁用</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="org-cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="org-save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;

        document.body.appendChild(modal);
        AddOrgModal.initEvents();
        AddOrgModal.loadParentOrgs();
        modal.classList.add('show');
    }

    static initEvents() {
        const modal = document.getElementById('addOrgModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = document.getElementById('org-cancel-btn');
        const form = modal.querySelector('.add-org-form');

        closeBtn.addEventListener('click', AddOrgModal.closeModal);
        cancelBtn.addEventListener('click', AddOrgModal.closeModal);
        modal.querySelector('.modal-overlay').addEventListener('click', AddOrgModal.closeModal);

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                AddOrgModal.closeModal();
            }
        });

        const fields = ['org-name', 'org-code', 'org-type', 'org-parent', 'org-leader'];
        fields.forEach(field => {
            const input = document.getElementById(field);
            input.addEventListener('input', () => {
                AddOrgModal.validateField(field, input.value);
                AddOrgModal.checkFormValidity(form);
            });
            input.addEventListener('change', () => {
                AddOrgModal.validateField(field, input.value);
                AddOrgModal.checkFormValidity(form);
            });
        });

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            AddOrgModal.submitForm(form);
        });
    }

    static loadParentOrgs() {
        const parentSelect = document.getElementById('org-parent');
        const orgs = OrgStructureManager.getAllOrganizations();

        orgs.forEach(org => {
            const option = document.createElement('option');
            option.value = org.id;
            option.textContent = org.name;
            parentSelect.appendChild(option);
        });
    }

    static validateField(field, value) {
        let isValid = true;
        let errorMessage = '';

        switch (field) {
            case 'org-name':
                if (!value.trim()) {
                    errorMessage = '组织名称不能为空';
                    isValid = false;
                } else if (value.length < 2 || value.length > 50) {
                    errorMessage = '组织名称长度为2-50个字符';
                    isValid = false;
                }
                break;

            case 'org-code':
                const codeRegex = /^[a-zA-Z0-9]+$/;
                if (!value.trim()) {
                    errorMessage = '组织代码不能为空';
                    isValid = false;
                } else if (!codeRegex.test(value)) {
                    errorMessage = '组织代码只能包含字母和数字';
                    isValid = false;
                }
                break;

            case 'org-type':
                if (!value) {
                    errorMessage = '请选择组织类型';
                    isValid = false;
                }
                break;

            case 'org-parent':
                if (value === '') {
                    errorMessage = '请选择上级组织';
                    isValid = false;
                }
                break;

            case 'org-leader':
                if (!value.trim()) {
                    errorMessage = '负责人不能为空';
                    isValid = false;
                }
                break;
        }

        const errorElement = document.getElementById(`${field}-error`);
        if (errorElement) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = errorMessage ? 'block' : 'none';
        }

        const inputElement = document.getElementById(field);
        if (inputElement) {
            if (isValid) {
                inputElement.classList.remove('is-invalid');
                inputElement.classList.add('is-valid');
            } else {
                inputElement.classList.remove('is-valid');
                inputElement.classList.add('is-invalid');
            }
        }

        return isValid;
    }

    static checkFormValidity(form) {
        const saveBtn = document.getElementById('org-save-btn');
        const nameValid = AddOrgModal.validateField('org-name', form['name'].value);
        const codeValid = AddOrgModal.validateField('org-code', form['code'].value);
        const typeValid = AddOrgModal.validateField('org-type', form['type'].value);
        const parentValid = AddOrgModal.validateField('org-parent', form['parentId'].value);
        const leaderValid = AddOrgModal.validateField('org-leader', form['leader'].value);

        saveBtn.disabled = !(nameValid && codeValid && typeValid && parentValid && leaderValid);
    }

    static submitForm(form) {
        const saveBtn = document.getElementById('org-save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const formData = {
            name: form['name'].value,
            code: form['code'].value,
            type: form['type'].value,
            parentId: parseInt(form['parentId'].value),
            leader: form['leader'].value,
            memberCount: 0,
            status: form['status'].value
        };

        setTimeout(() => {
            OrgStructureManager.addOrganization(formData);
            alert('新增组织成功');
            AddOrgModal.closeModal();

            const container = document.getElementById('org-structure');
            OrgStructureManager.loadContent(container);
        }, 1000);
    }

    static closeModal() {
        const modal = document.getElementById('addOrgModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        }
    }
}

// 修改组织模态框
class EditOrgModal {
    static showModal(orgData) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'editOrgModal';

        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>修改组织</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="edit-org-form">
                    <input type="hidden" id="edit-org-id" value="${orgData.id}">
                    <div class="form-group">
                        <label for="edit-org-name">组织名称</label>
                        <input type="text" id="edit-org-name" name="name" class="form-control" value="${orgData.name}" placeholder="2-50个字符" required>
                        <div class="error-text" id="edit-org-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-org-code">组织代码</label>
                        <input type="text" id="edit-org-code" name="code" class="form-control" value="${orgData.code}" disabled>
                    </div>
                    <div class="form-group">
                        <label for="edit-org-type">组织类型</label>
                        <select id="edit-org-type" name="type" class="form-control" required>
                            <option value="总部" ${orgData.type === '总部' ? 'selected' : ''}>总部</option>
                            <option value="学院" ${orgData.type === '学院' ? 'selected' : ''}>学院</option>
                            <option value="系部" ${orgData.type === '系部' ? 'selected' : ''}>系部</option>
                            <option value="班级" ${orgData.type === '班级' ? 'selected' : ''}>班级</option>
                        </select>
                        <div class="error-text" id="edit-org-type-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-org-parent">上级组织</label>
                        <select id="edit-org-parent" name="parentId" class="form-control" required>
                            <option value="0">无上级</option>
                        </select>
                        <div class="error-text" id="edit-org-parent-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-org-leader">负责人</label>
                        <input type="text" id="edit-org-leader" name="leader" class="form-control" value="${orgData.leader}" placeholder="负责人姓名" required>
                        <div class="error-text" id="edit-org-leader-error"></div>
                    </div>
                    <div class="form-group">
                        <label id="edit-org-status-label">状态</label>
                        <div class="custom-radio-group" role="radiogroup" aria-labelledby="edit-org-status-label" style="display: flex; gap: 20px;">
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="edit-org-status-active" name="status" value="active" ${orgData.status === 'active' ? 'checked' : ''}>
                                <label for="edit-org-status-active" style="margin-bottom: 0; margin-left: 8px;">启用</label>
                            </div>
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="edit-org-status-inactive" name="status" value="inactive" ${orgData.status === 'inactive' ? 'checked' : ''}>
                                <label for="edit-org-status-inactive" style="margin-bottom: 0; margin-left: 8px;">禁用</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="edit-org-cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="edit-org-save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;

        document.body.appendChild(modal);
        EditOrgModal.initEvents();
        EditOrgModal.loadParentOrgs(orgData.parentId);
        modal.classList.add('show');
    }

    static initEvents() {
        const modal = document.getElementById('editOrgModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = document.getElementById('edit-org-cancel-btn');
        const form = modal.querySelector('.edit-org-form');

        closeBtn.addEventListener('click', EditOrgModal.closeModal);
        cancelBtn.addEventListener('click', EditOrgModal.closeModal);
        modal.querySelector('.modal-overlay').addEventListener('click', EditOrgModal.closeModal);

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                EditOrgModal.closeModal();
            }
        });

        const fields = ['edit-org-name', 'edit-org-type', 'edit-org-parent', 'edit-org-leader'];
        fields.forEach(field => {
            const input = document.getElementById(field);
            input.addEventListener('input', () => {
                EditOrgModal.validateField(field, input.value);
                EditOrgModal.checkFormValidity();
            });
            input.addEventListener('change', () => {
                EditOrgModal.validateField(field, input.value);
                EditOrgModal.checkFormValidity();
            });
        });

        EditOrgModal.validateField('edit-org-name', document.getElementById('edit-org-name').value);
        EditOrgModal.validateField('edit-org-type', document.getElementById('edit-org-type').value);
        EditOrgModal.validateField('edit-org-parent', document.getElementById('edit-org-parent').value);
        EditOrgModal.validateField('edit-org-leader', document.getElementById('edit-org-leader').value);
        EditOrgModal.checkFormValidity();

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            EditOrgModal.submitForm(form);
        });
    }

    static loadParentOrgs(selectedParentId) {
        const parentSelect = document.getElementById('edit-org-parent');
        const orgs = OrgStructureManager.getAllOrganizations();

        orgs.forEach(org => {
            const option = document.createElement('option');
            option.value = org.id;
            option.textContent = org.name;
            if (org.id === selectedParentId) {
                option.selected = true;
            }
            parentSelect.appendChild(option);
        });
    }

    static validateField(field, value) {
        let isValid = true;
        let errorMessage = '';

        switch (field) {
            case 'edit-org-name':
                if (!value.trim()) {
                    errorMessage = '组织名称不能为空';
                    isValid = false;
                } else if (value.length < 2 || value.length > 50) {
                    errorMessage = '组织名称长度为2-50个字符';
                    isValid = false;
                }
                break;

            case 'edit-org-type':
                if (!value) {
                    errorMessage = '请选择组织类型';
                    isValid = false;
                }
                break;

            case 'edit-org-parent':
                if (value === '') {
                    errorMessage = '请选择上级组织';
                    isValid = false;
                }
                break;

            case 'edit-org-leader':
                if (!value.trim()) {
                    errorMessage = '负责人不能为空';
                    isValid = false;
                }
                break;
        }

        const errorElement = document.getElementById(`${field}-error`);
        if (errorElement) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = errorMessage ? 'block' : 'none';
        }

        const inputElement = document.getElementById(field);
        if (inputElement) {
            if (isValid) {
                inputElement.classList.remove('is-invalid');
                inputElement.classList.add('is-valid');
            } else {
                inputElement.classList.remove('is-valid');
                inputElement.classList.add('is-invalid');
            }
        }

        return isValid;
    }

    static checkFormValidity() {
        const saveBtn = document.getElementById('edit-org-save-btn');
        const nameValid = EditOrgModal.validateField('edit-org-name', document.getElementById('edit-org-name').value);
        const typeValid = EditOrgModal.validateField('edit-org-type', document.getElementById('edit-org-type').value);
        const parentValid = EditOrgModal.validateField('edit-org-parent', document.getElementById('edit-org-parent').value);
        const leaderValid = EditOrgModal.validateField('edit-org-leader', document.getElementById('edit-org-leader').value);

        saveBtn.disabled = !(nameValid && typeValid && parentValid && leaderValid);
    }

    static submitForm(form) {
        const saveBtn = document.getElementById('edit-org-save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const orgId = parseInt(document.getElementById('edit-org-id').value);
        const updateData = {
            name: form['name'].value,
            type: form['type'].value,
            parentId: parseInt(form['parentId'].value),
            leader: form['leader'].value,
            status: form['status'].value
        };

        setTimeout(() => {
            OrgStructureManager.updateOrganization(orgId, updateData);
            alert('修改组织成功');
            EditOrgModal.closeModal();

            const container = document.getElementById('org-structure');
            OrgStructureManager.loadContent(container);
        }, 1000);
    }

    static closeModal() {
        const modal = document.getElementById('editOrgModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        }
    }
}